﻿using System.Data;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using DevelopTool.Bll.DbBlls;
using DevelopTool.Common;
using DevelopTool.Dal;
using DevelopTool.Model.DbModels;
using DevelopTool.My.Plugins.Common;

namespace DevelopTool.My.Plugins.Bll
{
    public class ReportViewBll
    {
        /// <summary>
        /// 数据库操作类
        /// </summary>
        private OracleDbDal oracleDbDal;

        public ReportViewBll(DbInfo dbInfo)
        {
            oracleDbDal = new OracleDbDal(new OracleDbBll(dbInfo).GetConnectionString());
        }

        /// <summary>
        /// 获取报表集合
        /// </summary>
        /// <param name="dataBase"></param>
        /// <returns></returns>
        public DataTable GetReports()
        {
            string getReport_Sql = $"SELECT R.ID,R.NAME,R.TYPE,R.ISVALID,R.VERSION,R.CONTENT,'' AS SQL,'' AS XMLDATA FROM QUICKREPORT_REPORTS R";

            var dataTable = oracleDbDal.GetDataTable(getReport_Sql);

            if(dataTable == null || dataTable.Rows.Count <= 0) return dataTable;

            for(int i = 0 ; i < dataTable.Rows.Count ; i++)
            {
                //解密报表内容
                string contentXml = ReportEncryptionHelper.Decrypt(Encoding.Default.GetString((byte[])dataTable.Rows[i]["CONTENT"]));

                dataTable.Rows[i]["XMLDATA"] = contentXml;

                dataTable.Rows[i]["SQL"] = GetReportSqlStr(contentXml);
            }

            dataTable.Columns.Remove("CONTENT");//删除原始的列，防止占用过多内存
            return dataTable;
        }


        /// <summary>
        /// 解析报表xml获取sql节点的值
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private string GetReportSqlStr(string xml)
        {
            if(xml.IsEmpty()) return string.Empty;
            XElement xe = XElement.Parse(xml);
            var mainReportSetting = xe.Elements().FirstOrDefault(it => it.Name.LocalName.Equals("MainReportSetting"));
            if(mainReportSetting == null) return string.Empty;
            var sql = mainReportSetting.Elements().FirstOrDefault(it => it.Name.LocalName.Equals("SQL"));
            if(sql == null) return string.Empty;
            return sql.Value;
        }

    }
}
